package org.management.config.web;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * @title: WebMvcConfig
 * @description: restApi 访问方式配置
 * @author: jiangyan
 * @date:  2019/1/24
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Value("${corsMappings.origins}")
    private String originsUrls;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        String [] originsArray = originsUrls.split(",");
        registry.addMapping("/**")
        		.allowCredentials(true)
                .allowedOrigins(originsArray)
                .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH","OPTIONS")
                .allowedHeaders("*").maxAge(3600);
    }
}
